<template>
  <div class="recycle-container">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <div class="left-operations">
        <a-button type="primary" @click="fetchRecycleList">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
        <a-button danger @click="handleBatchDelete" :disabled="selectedFileKeys.length === 0">
          <template #icon><DeleteOutlined /></template>
          批量删除
        </a-button>
        <a-button
          type="primary"
          @click="handleBatchRestore"
          :disabled="selectedFileKeys.length === 0"
        >
          <template #icon><UndoOutlined /></template>
          批量恢复
        </a-button>
      </div>

      <a-input-search
        v-model:value="searchParams.fileNameFuzzy"
        placeholder="搜索文件..."
        style="width: 260px"
        @search="handleSearch"
      />
    </div>

    <!-- 文件列表 -->
    <div class="file-list">
      <a-table
        :columns="columns"
        :data-source="recycleList"
        :row-selection="{
          selectedRowKeys: selectedFileKeys,
          onChange: onSelectChange,
        }"
        :row-key="record => record.fileId"
        :pagination="{
          total: totalCount,
          current: searchParams.pageNo,
          pageSize: searchParams.pageSize,
          onChange: handlePageChange,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: total => `共 ${total} 条`,
        }"
        class="recycle-table"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <!-- 文件名列 -->
          <template v-if="column.key === 'fileName'">
            <div class="file-cell">
              <div
                class="file-icon"
                :class="{
                  'has-cover': record.fileCover && (record.fileType === 3 || record.fileType === 1),
                }"
              >
                <!-- 文件夹 -->
                <template v-if="record.folderType">
                  <FolderFilled class="folder-icon" />
                </template>
                <!-- 图片文件 -->
                <template v-else-if="record.fileType === 3">
                  <img v-if="record.fileCover" :src="record.fileCover" :alt="record.fileName" />
                  <FileImageOutlined v-else class="file-type-icon" />
                </template>
                <!-- 视频文件 -->
                <template v-else-if="record.fileType === 1">
                  <img v-if="record.fileCover" :src="record.fileCover" :alt="record.fileName" />
                  <PlaySquareOutlined v-else class="file-type-icon" />
                </template>
                <!-- 音频文件 -->
                <template v-else-if="record.fileType === 2">
                  <CustomerServiceOutlined class="file-type-icon" />
                </template>
                <!-- PDF文件 -->
                <template v-else-if="record.fileType === 4">
                  <FilePdfOutlined class="file-type-icon" />
                </template>
                <!-- Word文档 -->
                <template v-else-if="record.fileType === 5">
                  <FileWordOutlined class="file-type-icon" />
                </template>
                <!-- Excel文件 -->
                <template v-else-if="record.fileType === 6">
                  <FileExcelOutlined class="file-type-icon" />
                </template>
                <!-- 文本文件 -->
                <template v-else-if="record.fileType === 7">
                  <FileTextOutlined class="file-type-icon" />
                </template>
                <!-- 代码文件 -->
                <template v-else-if="record.fileType === 8">
                  <CodeOutlined class="file-type-icon" />
                </template>
                <!-- 压缩文件 -->
                <template v-else-if="record.fileType === 9">
                  <FileZipOutlined class="file-type-icon" />
                </template>
                <!-- 其他文件 -->
                <template v-else>
                  <FileOutlined class="file-type-icon" />
                </template>
              </div>
              <span class="file-name">{{ record.fileName || '未命名文件' }}</span>
            </div>
          </template>

          <!-- 操作列 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleRestore(record)"> 恢复 </a-button>
              <a-button type="link" danger @click="handleDelete(record)"> 删除 </a-button>
            </a-space>
          </template>

          <!-- 文件大小列 -->
          <template v-if="column.key === 'fileSize'">
            {{ formatSize(record.fileSize) }}
          </template>

          <!-- 删除时间列 -->
          <template v-if="column.key === 'delTime'">
            {{ formatDelTime(record.delTime) }}
          </template>
        </template>
      </a-table>

      <!-- 空状态 -->
      <div v-if="recycleList.length === 0" class="empty-state">
        <div class="empty-icon">
          <DeleteOutlined style="font-size: 48px; color: #bfbfbf" />
        </div>
        <div class="empty-text">回收站是空的</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { message } from 'ant-design-vue'
  import {
    ReloadOutlined,
    DeleteOutlined,
    UndoOutlined,
    FolderFilled,
    FileOutlined,
    FileImageOutlined,
    PlaySquareOutlined,
    CustomerServiceOutlined,
    FilePdfOutlined,
    FileWordOutlined,
    FileExcelOutlined,
    FileTextOutlined,
    CodeOutlined,
    FileZipOutlined,
  } from '@ant-design/icons-vue'
  import dayjs from 'dayjs'
  import {
    loadRecycleListUsingPost,
    recoverFileUsingPost,
    delRecycleFileUsingPost,
  } from '@/api/wenjianmokuai'

  // 表格列定义
  const columns = [
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
      width: '40%',
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: '15%',
    },
    {
      title: '删除时间',
      dataIndex: 'delTime',
      key: 'delTime',
      width: '25%',
    },
    {
      title: '操作',
      key: 'action',
      width: '20%',
    },
  ]

  // 搜索参数
  const searchParams = reactive({
    pageNo: 1,
    pageSize: 10,
    fileNameFuzzy: '',
  })

  // 列表数据
  const recycleList = ref([])
  const totalCount = ref(0)
  const selectedFileKeys = ref<string[]>([])

  // 格式化文件大小
  const formatSize = (bytes: string | number) => {
    const size = Number(bytes)
    if (!size || size === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(size) / Math.log(k))
    return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化删除时间
  const formatDelTime = (time: string) => {
    if (!time) return '未知时间'
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
  }

  // 获取回收站列表
  const fetchRecycleList = async () => {
    try {
      const res = await loadRecycleListUsingPost({
        pageNo: searchParams.pageNo.toString(),
        pageSize: searchParams.pageSize.toString(),
        fileNameFuzzy: searchParams.fileNameFuzzy,
      })

      if (res.data?.code === 200) {
        recycleList.value = (res.data.data.list || []).map(item => ({
          ...item,
          fileSize: item.fileSize || '0',
          folderType: item.folderType || false,
          fileType: item.fileType || null,
          fileName: item.fileName || '未命名文件',
        }))
        totalCount.value = parseInt(res.data.data.totalCount) || 0
      }
    } catch (error) {
      console.error('获取回收站列表失败:', error)
      message.error('获取回收站列表失败')
    }
  }

  // 处理搜索
  const handleSearch = () => {
    searchParams.pageNo = 1
    fetchRecycleList()
  }

  // 处理页码变化
  const handlePageChange = (page: number, pageSize?: number) => {
    searchParams.pageNo = page
    if (pageSize) {
      searchParams.pageSize = pageSize
    }
    fetchRecycleList()
  }

  // 处理选择变化
  const onSelectChange = (selectedRowKeys: string[]) => {
    selectedFileKeys.value = selectedRowKeys
  }

  // 处理单个文件恢复
  const handleRestore = async (record: any) => {
    try {
      const res = await recoverFileUsingPost({
        fileIds: record.fileId,
      })

      if (res.data?.code === 200) {
        message.success('恢复成功')
        fetchRecycleList()
      } else {
        message.error(res.data?.message || '恢复失败')
      }
    } catch {
      message.error('恢复失败')
    }
  }

  // 处理单个文件删除
  const handleDelete = async (record: any) => {
    try {
      const res = await delRecycleFileUsingPost({
        fileIds: record.fileId,
      })

      if (res.data?.code === 200) {
        message.success('删除成功')
        fetchRecycleList()
      } else {
        message.error(res.data?.message || '删除失败')
      }
    } catch {
      message.error('删除失败')
    }
  }

  // 处理批量恢复
  const handleBatchRestore = async () => {
    if (selectedFileKeys.value.length === 0) return

    try {
      const res = await recoverFileUsingPost({
        fileIds: selectedFileKeys.value.join(','),
      })

      if (res.data?.code === 200) {
        message.success('批量恢复成功')
        selectedFileKeys.value = []
        fetchRecycleList()
      } else {
        message.error(res.data?.message || '批量恢复失败')
      }
    } catch {
      message.error('批量恢复失败')
    }
  }

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (selectedFileKeys.value.length === 0) return

    try {
      const res = await delRecycleFileUsingPost({
        fileIds: selectedFileKeys.value.join(','),
      })

      if (res.data?.code === 200) {
        message.success('批量删除成功')
        selectedFileKeys.value = []
        fetchRecycleList()
      } else {
        message.error(res.data?.message || '批量删除失败')
      }
    } catch {
      message.error('批量删除失败')
    }
  }

  // 初始化
  fetchRecycleList()
</script>

<style scoped lang="less">
  .recycle-container {
    padding: 0;
    background: var(--theme-surface);
    height: calc(100vh - 64px);
    display: flex;
    flex-direction: column;
    position: relative;
    transition: all 0.3s ease;
  }

  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px 24px 16px;
    background: var(--theme-surface);
    border-bottom: 1px solid var(--theme-border);
    position: sticky;
    top: 0;
    z-index: 10;
    transition: all 0.3s ease;
  }

  .left-operations {
    display: flex;
    gap: 8px;
  }

  .search-input {
    width: 250px;
  }

  .file-list {
    flex: 1;
    overflow: auto;
    padding: 0 24px 24px;
  }

  .file-cell {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .file-icon {
    width: 24px;
    height: 24px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    &.has-cover {
      border-radius: 4px;
      overflow: hidden;
    }

    .folder-icon {
      font-size: 24px;
      color: #fac858;
    }

    .file-type-icon {
      font-size: 24px;
      color: #1890ff;
    }
  }

  .video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .file-name {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 48px 0;
  }

  .empty-icon {
    margin-bottom: 16px;
  }

  .empty-text {
    color: #8c8c8c;
    font-size: 14px;
  }

  .recycle-table {
    flex: 1;
    :deep(.ant-table-wrapper) {
      height: 100%;
    }
    :deep(.ant-table) {
      height: 100%;
    }
    :deep(.ant-table-tbody > tr > td) {
      padding: 12px 8px;
    }
  }
</style>
